package video.com.transition;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.List;

@Component
public class VideoTransaction {

    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 编程式事务控制方式 细化事务粒度
     * @param transactionFunc
     * @throws Exception 当执行传入函数出现异常时，回滚事务并抛出异常
     */
    public void execute(TransactionFunc transactionFunc) throws Exception{

        List<Exception> exceptions = new ArrayList<>();

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {
                    transactionFunc.execute();
                } catch (Exception e) {
                    e.printStackTrace();

                    exceptions.add(e);

                    transactionStatus.setRollbackOnly();
                }
            }
        });

        if(!exceptions.isEmpty()){
            throw exceptions.get(0);
        }
    }
}
